package top.tupobi.flutterdemo


import android.app.*
import android.content.Context
import android.content.Intent
import android.net.Uri
import android.os.Build
import android.widget.RemoteViews
import android.widget.Toast
import androidx.core.content.FileProvider
import io.flutter.embedding.engine.plugins.FlutterPlugin
import io.flutter.embedding.engine.plugins.activity.ActivityAware
import io.flutter.embedding.engine.plugins.activity.ActivityPluginBinding
import io.flutter.plugin.common.MethodCall
import io.flutter.plugin.common.MethodChannel
import java.io.File


//1、因为dart 语言和flutter 快速发展，在插件的java文件中，会有 onAttachedToEngine 和 registerWith 两个方法，目的是将类注册到dart对应的MethodChannel 中，
//
//这两个方法功能一致，在一个项目中，只会触发其中一个方法，如果你使用的是 flutter >= 1.12.x ，则只会触发 onAttachedToEngine方法，如果是 flutter <= 1.12.x 版本则会触发 registerWith .
class FlutterNativePlugin : FlutterPlugin, MethodChannel.MethodCallHandler, ActivityAware {

    companion object {
        lateinit var activity: Activity
    }

    private lateinit var views: RemoteViews
    private lateinit var nm: NotificationManager
    private lateinit var notification: Notification
    private var flag = true

    override fun onAttachedToEngine(binding: FlutterPlugin.FlutterPluginBinding) {
        val channel = MethodChannel(binding.flutterEngine.dartExecutor, "top.tupobi.flutterdemo/test")
        channel.setMethodCallHandler(FlutterNativePlugin())

//        val methodChannel = MethodChannel(binding.binaryMessenger, Constants.NATIVE_VOICE_CHANNEL)
//        methodChannel.setMethodCallHandler(FlutterVoiceNativePlugin())
    }

//    companion object {
//        fun registerWith(registrar: PluginRegistry.Registrar) {
//            val channel = MethodChannel(registrar.messenger(), "top.tupobi.flutterdemo/test")
//            channel.setMethodCallHandler(FlutterNativePlugin())
//        }
//    }

    override fun onDetachedFromEngine(binding: FlutterPlugin.FlutterPluginBinding) {
    }

    override fun onMethodCall(call: MethodCall, result: MethodChannel.Result) {
        when (call.method) {
            "getData" -> {
                val name = call.argument<String>("name");
                val age = call.argument<Int>("age")
                Toast.makeText(activity, "name == $name, age == $age", Toast.LENGTH_LONG).show()
                result.success("android原生执行：：\n" + call.arguments.toString() + "\n" + call.method)

            }
            "sendNotification" -> {
                val progress = call.argument<Int>("progress")
                sendNotification(progress)
            }
            "installApk" -> {
                println("安装APK")
                val filePath = call.argument<String>("filePath")
                val res = installApk(filePath)
                result.success(res)
            }
            else -> {
                result.notImplemented()
            }
        }
    }

    private fun sendNotification(progress: Int?) {
        if (progress == null) {
            return
        }
        views = RemoteViews(activity.packageName, R.layout.download_view)
        nm = activity.getSystemService(Context.NOTIFICATION_SERVICE) as NotificationManager
        val builder1 = Notification.Builder(activity)
        //8.0以上必加
        //8.0以上必加
        builder1.setSmallIcon(R.mipmap.ic_launcher)
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) { //8.0以上加
            builder1.setChannelId(activity.packageName)
            //9.0以上加
            val channel = NotificationChannel(
                    activity.packageName,
                    "会话类型",  //这块Android9.0分类的比较完整，你创建多个这样的东西，你可以在设置里边显示那个或者第几个
                    NotificationManager.IMPORTANCE_HIGH
            )
            nm.createNotificationChannel(channel)
        }
        notification = builder1.build()
        notification.contentView = views
        notification.icon = R.mipmap.ic_launcher
        notification.tickerText = ""
        notification.`when` = System.currentTimeMillis()
        notification.defaults = Notification.DEFAULT_LIGHTS
        notification.contentView = views
        val pi: PendingIntent = PendingIntent.getActivity(activity, 0, Intent(activity, MainActivity::class.java), 0)
        notification.contentIntent = pi


        if (progress in 0..99) {
            views.setTextViewText(R.id.tvProcess, "已下载$progress%")
            views.setProgressBar(R.id.progressBar, 100, progress, false)
            notification.contentView = views
            nm.notify(1, notification)
        } else if (progress == 100) {
            nm.cancel(1)
        }
    }

    private fun installApk(filePath: String?): Int {
        if (filePath.isNullOrEmpty()) {
            return 0
        } else {
            val intent = Intent(Intent.ACTION_VIEW)
            val apkFile = File(filePath)
            try { //兼容7.0
                if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.N) {
                    intent.addFlags(Intent.FLAG_GRANT_READ_URI_PERMISSION)
                    val contentUri: Uri = FileProvider.getUriForFile(activity, activity.packageName.toString() + ".fileProvider", apkFile)
                    intent.setDataAndType(contentUri, "application/vnd.android.package-archive")
                    //兼容8.0
//                    if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.O) {
//                        val hasInstallPermission: Boolean = activity.packageManager.canRequestPackageInstalls()
//                        if (!hasInstallPermission) {
//
//                            startInstallPermissionSettingActivity()
//                            return
//                        }
//                    }
                } else {
                    intent.setDataAndType(Uri.fromFile(apkFile), "application/vnd.android.package-archive")
                    intent.flags = Intent.FLAG_ACTIVITY_NEW_TASK
                }
                activity.startActivity(intent)
                return 1
            } catch (e: Throwable) {
                e.printStackTrace()
                return 0
            }
        }
    }

    override fun onDetachedFromActivity() {
    }

    override fun onReattachedToActivityForConfigChanges(binding: ActivityPluginBinding) {
    }

    override fun onAttachedToActivity(binding: ActivityPluginBinding) {
        activity = binding.activity
    }

    override fun onDetachedFromActivityForConfigChanges() {
    }
}